package net.borderwars.userserver;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;

/**
 * @author ehubbard
 *         Date: Apr 14, 2006
 *         Time: 9:21:35 AM
 */
public class ByteBufferInputStream extends InputStream {
    LinkedList<int[]> buffers = new LinkedList<int[]>();
    // Semaphore sem = new Semaphore (0);
    int availableBytes = 0;

    int currentReadIndex = 0;

    public int available() throws IOException {
        return (availableBytes);
    }

    public void add(byte[] in) {
        int data[] = new int[in.length];
        for (int x = 0; x < in.length; x++) {
            if (in[x] < 0)
                data[x] = in[x] + 256;
            else
                data[x] = in[x];
        }

        buffers.add(data);
        availableBytes += in.length;
        //   sem.release (in.length);
    }

    synchronized public int read(byte b[], int off, int len) throws IOException {
        for (int x = 0; x < len; x++, off++) {
            int d = _read();
            b[off] = (byte) d;
        }
        return (len);
    }

    synchronized public int read() throws IOException {
        return (_read());
    }

    /**
     * before calling this make sure to aquire the right amount of counters on the semaphore
     * This method is not synchronized.. it is called by many others.. so we'd rather not
     *
     * @return
     * @throws IOException
     */
    private int _read() throws IOException {
        int data[] = buffers.getFirst();
        int x = data[currentReadIndex++];
        nextBuffer(data);
        availableBytes--;
        return (x);
    }

    private void nextBuffer(final int[] data) {
        if (currentReadIndex >= data.length) { // if we just grabbed the last byte
            buffers.removeFirst(); // get rid of the array
            currentReadIndex = 0; // and move our index to position 0 on the new array
        }
    }

    public boolean markSupported() {
        return (false);
    }
}
